//
//  DataControl.m
//  tcpoctest
//
//  Created by gump on 10/26/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "DataControl.h"
#import "UserInfo.h"
#import <pthread.h>
#import "RegexKitLite.h"
#import "headimagedb.h"
#import "CareDataSource.h"
#import "PromptLoginDataSource.h"
#import "FirendCircleDataSource.h"
#import "FirCirLocalResourceDataSource.h"
#import "FirCirCommentDataSource.h"
#import "LocalPathDataSource.h"
#import "FirCirNewsDataSource.h"
#import "FirCirCommentInfo.h"
#import "FirCirNewsMailDataSource.h"
#import "FirCirBgImageDataSource.h"
#import "FirCirPersonDataSource.h"
#import "VersionDataSource.h"
#import "OnlinePeopleDataSource.h"
#import "UICommendDataSource.h"
#import "LogicCommendDataSource.h"

#import "GiftListDataSource.h"
#import "GiftInfoDataSource.h"
#import "GiftMessageDataSource.h"
#import "giftStroageDataSource.h"

#import "RankListDataSource.h"

#import "taskDataSource.h"

#import "personDataSource.h"

#import "chatDataSource.h"

#import "MessageDataSource.h"

#import "TelepathyDataSource.h"

#import "bigHeadImageDataSource.h"

@implementation DataControl

static DataControl *sharedInstance = nil;

+(DataControl*)shareControl
{
    
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init]; // assignment not done here
        }
    }
    return (DataControl*)sharedInstance;
}

-(id)init
{
    self =  [super init];
    
    if(self)
    {
        self.mapArray = [[NSMutableArray alloc] init];
        
        self.careds = [[CareDataSource alloc] init];
        self.becareds = [[CareDataSource alloc] init];
        
        self.currentFI = nil;
        
        self.mlatitude = 39895730.f;
        self.mlongitude = 116359827.f;
        
        self.nearPeopleDistanceDic = [[NSMutableDictionary alloc] init];
        self.nearPeopleShowArr = [[NSMutableArray alloc] init];
        
        self.blogin = false;
        self.bfirstlogin = true;
        
        self.iImage = [[UIImage alloc] init];
        
        self.iSerchPPNum = 0;
        
        self.strChangeName = @"";
        self.ichangeSex = 0;
        self.ichangeAge = 0;
        self.strChangeOldPS = @"";
        self.strChangeNewPS = @"";
        self.strChangeSign = @"";
        
        self.HeadImageDic = [[NSMutableDictionary alloc] init];
        
        self.ichangeNeedCheck = 1;
        
        self.mloginType = LT_MAIL;
        
        self.headImageRequestSet = [[NSMutableSet alloc] init];
        self.headImageSendArr = [[NSMutableArray alloc] init];
        
        self.firendInfoDic = [[NSMutableDictionary alloc] init];
        self.firendInfoRequestSet = [[NSMutableSet alloc] init];
        self.firendInfoSendArr = [[NSMutableArray alloc] init];
        
        self.mBadgeCount = 0;
        self.iGameState = GMS_NULL;
        self.miOldGameState = GMS_NULL;
        
        self.nearFemaleDic = [[NSMutableDictionary alloc] init];
        self.nearFemaleShowArr = [[NSMutableArray alloc] init];
        
        self.nearMaleDic = [[NSMutableDictionary alloc] init];
        self.nearMaleShowArr = [[NSMutableArray alloc] init];
        
        self.nearPeopleCurShowArr = nil;
        self.mVisitNearPeopleTime = 0.0f;
        self.mVisitNPFamaleTime = 0.0f;
        self.mVisitNPMaleTime = 0.0f;
        self.nearPeopleCurDic = nil;
        
        self.iLoginFailID = LFM_MAIL;
        self.iConfigFailID = CM_FAIL;
        
        self.reportMail = nil;
        
        pthread_mutex_init(&mymutexFirendCir, 0);
        
        self.promptloginDS = [[PromptLoginDataSource alloc] init];
        
        self.fircirDS = [[FirendCircleDataSource alloc] init];
        self.fcLocalRecDS = [[FirCirLocalResourceDataSource alloc] init];
        self.fccommentDS = [[FirCirCommentDataSource alloc] init];
        self.fcnewsDS = [[FirCirNewsDataSource alloc] init];
        self.fcnewsmailDS = [[FirCirNewsMailDataSource alloc] init];
        self.fcBgImageDS = [[FirCirBgImageDataSource alloc] init];
        self.fcPersonDS = [[FirCirPersonDataSource alloc] init];
        
        self.localpathds = [[LocalPathDataSource alloc] init];
        
        self.verDS = [[VersionDataSource alloc] init];
        self.OnlinePeoDS = [[OnlinePeopleDataSource alloc] init];
        
        self.UICommendDS = [[UICommendDataSource alloc] init];
        self.LCDS = [[LogicCommendDataSource alloc] init];
        
        self.giftlistDS = [[GiftListDataSource alloc] init];
        self.giftInfoDS = [[GiftInfoDataSource alloc] init];
        self.giftMessageDS = [[GiftMessageDataSource alloc] init];
        self.giftStroageDS = [[giftStroageDataSource alloc] init];
        
        self.ranklistDS = [[RankListDataSource alloc] init];
        
        self.taskDS = [[taskDataSource alloc] init];
        
        self.personDS = [[personDataSource alloc] init];
        
        self.chatDS = [[chatDataSource alloc] init];
        
        self.messageDS = [[MessageDataSource alloc] init];
        
        self.TelepathyDS = [[TelepathyDataSource alloc] init];
        
        self.bigHIDS = [[bigHeadImageDataSource alloc] init];
    }
    
    return self;
}

-(void)SetLoginFailID:(int)failID
{
    self.iLoginFailID = failID;
}

-(void)SetGameState:(int)state
{
    self.miOldGameState = self.iGameState;
    self.iGameState = state;
}

-(void)setHeadImage:(UIImage *)hi
{
    self.iImage = hi;
}

-(void)setCurrentFirendInfo:(FirendInfo *)fi
{
    self.currentFI = fi;
}

-(void)SetChangeName:(NSString *)strname
{
    self.strChangeName = strname;
}

-(void)SetUpdateUserType:(int)itype
{
    self.iUUT = itype;
}

-(void)SetChangeSex:(int)isex
{
    self.ichangeSex = isex;
}

-(void)SetChangeAge:(int)iage
{
    self.ichangeAge = iage;
}

-(void)SetChangeSign:(NSString *)strsign
{
    self.strChangeSign = strsign;
}

-(void)setSearchPPNum:(int)ppnum
{
    self.iSerchPPNum = ppnum;
}

-(void)SetChangeCheck:(int)icheck
{
    self.ichangeNeedCheck = icheck;
}

-(void)SetLoginType:(int)type
{
    self.mloginType = type;
}

-(FirendInfo *)SearchInfo:(NSString *)mail
{
    
    FirendInfo * fi = [self.firendInfoDic objectForKey:mail];
    if (fi == nil && mail != nil)
    {
        if (![self.firendInfoRequestSet containsObject:mail]) {
            [self.firendInfoSendArr addObject:mail];
            [self.firendInfoRequestSet addObject:mail];
            [self.LCDS addLogicCommand:LC_SENDREQUESTINFO];
        }
    }
    
    return fi;
}

-(void)RefreshInfoByNet:(NSString *)mail
{
    if (mail != nil && ![self.firendInfoRequestSet containsObject:mail]) {
        
        [self.firendInfoSendArr addObject:mail];
        [self.firendInfoRequestSet addObject:mail];
        [self.LCDS addLogicCommand:LC_SENDREQUESTINFO];
    }

}

-(NSString *)SearchHeadImage:(NSString *)mail
{
    NSString *url = [self.HeadImageDic objectForKey:mail];
    if (url == nil)
    {
        if (![self.headImageRequestSet containsObject:mail]) {
            
            [self.headImageSendArr addObject:mail];
            [self.headImageRequestSet addObject:mail];
            [self.LCDS addLogicCommand:LC_SENDREQUESTHI];
        }
    }
    
    return url;
}



-(void)UpdateUserImage
{
    NSString *urlpath = @"";
    NSString *strname = getFileNameWithDate(FT_HEADIMAGE);
    strname = [NSString stringWithFormat:@"%@%@",strname,self.personDS.uinfo.mail];
    
    urlpath =[[[DataControl shareControl].localpathds headimagePath] stringByAppendingPathComponent:strname];
    NSData *data = UIImageJPEGRepresentation(self.iImage, JPG_COMPRESS_RATE);
    BOOL bsuccess = [data writeToFile:urlpath atomically:YES];
    
    do {
        
        if (!bsuccess) {
            break;
        }
        
        [[DataBaseCtrol shareControl].headimagedatabase insertHeadImageUrl:self.personDS.uinfo.mail withURL:urlpath];
        
        NSString *oldurl = [[DataControl shareControl].HeadImageDic objectForKey:self.personDS.uinfo.mail];
        if(oldurl != nil && ![oldurl isEqualToString:@""])
        {
            [[FileManager shareControl] deleteFile:oldurl];
        }
                
        [[DataControl shareControl].HeadImageDic setObject:urlpath forKey:self.personDS.uinfo.mail];
        
    } while (false);
}

-(void)UpdateUserImageFromNet:(NSString *)mail
{
    [[DataBaseCtrol shareControl].headimagedatabase deleteHImageByMail:mail];
    [[DataControl shareControl].HeadImageDic removeObjectForKey:mail];
    
    [self SearchHeadImage:mail];
}

-(bool)IsNeedVisitNearPeople
{
    bool bvisit = true;
    
    
    do {
        
        if (self.nearPeopleCurShowArr == nil || [self.nearPeopleCurShowArr count] == 0) {
            break;
        }
        
        if (self.nearPeopleShowArr == nil || [self.nearPeopleShowArr count] == 0) {
            break;
        }
        
        if (self.mVisitNearPeopleTime - 0.0f < 0.001)
        {
            self.mVisitNearPeopleTime = CFAbsoluteTimeGetCurrent();
            
            break;
        }
        else
        {
            CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
            
            float diff = fabsf(start - self.mVisitNearPeopleTime);
            
            if (diff - NEARPEOPLE_VISIT_TIME > 0.001)
            {
                self.mVisitNearPeopleTime = start;
            }
            else
            {
                bvisit = false;
            }
        }
    } while (false);
    
    
    return bvisit;
}

-(bool)IsNeedVisitNPFamale
{
    bool bvisit = true;
    
    
    do {
        
        if (self.nearPeopleCurShowArr == nil || [self.nearPeopleCurShowArr count] == 0) {
            break;
        }
        
        if (self.nearFemaleShowArr == nil || [self.nearFemaleShowArr count] == 0) {
            break;
        }
        
        if (self.mVisitNPFamaleTime - 0.0f < 0.001)
        {
            self.mVisitNPFamaleTime = CFAbsoluteTimeGetCurrent();
            
            break;
        }
        else
        {
            CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
            
            float diff = fabsf(start - self.mVisitNPFamaleTime);
            
            if (diff - NEARPEOPLE_VISIT_TIME > 0.001)
            {
                self.mVisitNPFamaleTime = start;
            }
            else
            {
                bvisit = false;
            }
        }
    } while(false);
    
    
    return bvisit;
}

-(bool)IsNeedVisitNPMale
{
    bool bvisit = true;
    
    
    do {
        
        if (self.nearPeopleCurShowArr == nil || [self.nearPeopleCurShowArr count] == 0) {
            break;
        }
        
        if (self.nearMaleShowArr == nil || [self.nearMaleShowArr count] == 0) {
            break;
        }
        
        if (self.mVisitNPMaleTime - 0.0f < 0.001)
        {
            self.mVisitNPMaleTime = CFAbsoluteTimeGetCurrent();
            
            break;
        }
        else
        {
            CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
            
            float diff = fabsf(start - self.mVisitNPMaleTime);
            
            if (diff - NEARPEOPLE_VISIT_TIME > 0.001)
            {
                self.mVisitNPMaleTime = start;
            }
            else
            {
                bvisit = false;
            }
        }
    } while (false);
    
    
    return bvisit;
}

-(void)clearNearPeopleData
{
    [self.nearPeopleDistanceDic removeAllObjects];
    [self.nearPeopleShowArr removeAllObjects];
    [self.nearMaleDic removeAllObjects];
    [self.nearMaleShowArr removeAllObjects];
    [self.nearFemaleDic removeAllObjects];
    [self.nearFemaleShowArr removeAllObjects];
    
    if (self.nearPeopleCurDic != nil) {
        [self.nearPeopleCurDic removeAllObjects];
    }
    
    if (self.nearPeopleCurShowArr != nil) {
        [self.nearPeopleCurShowArr removeAllObjects];
    }
}

-(void)clearData
{
    [self clearNearPeopleData];
    
    [self.careds RemoveAllShowArr];
    [self.becareds RemoveAllShowArr];
    [self.messageDS DelAllMsgArr];
    [self.giftMessageDS delAllMessage];
    [self.taskDS ClearState];
    [self.fcPersonDS RemoveAllDelArr];
    
    setOnLineOrder(OLOT_NULL);
}

-(void)SetConfigFailID:(int)len
{
    self.iConfigFailID = len;
}

-(void)SetReportMail:(NSString *)mail
{
    self.reportMail = mail;
}

-(void)UpdateImageWithMail:(NSString *)mail withImage:(UIImage *)image
{
    NSString *urlpath = @"";
    NSString *strname = getFileNameWithDate(FT_HEADIMAGE);
    strname = [NSString stringWithFormat:@"%@%@",strname,self.personDS.uinfo.mail];
    
    urlpath =[[[DataControl shareControl].localpathds headimagePath] stringByAppendingPathComponent:strname];
    
    
    NSData *data = UIImageJPEGRepresentation(image, JPG_COMPRESS_RATE);
    BOOL bsuccess = [data writeToFile:urlpath atomically:YES];
    
    do {
        
        if (!bsuccess) {
            break;
        }
        
        [[DataBaseCtrol shareControl].headimagedatabase insertHeadImageUrl:mail withURL:urlpath];
        
        NSString *oldurl = [[DataControl shareControl].HeadImageDic objectForKey:mail];
        if(oldurl != nil && ![oldurl isEqualToString:@""])
        {
            [[FileManager shareControl] deleteFile:oldurl];
        }
        
        [[DataControl shareControl].HeadImageDic setObject:urlpath forKey:mail];
        
    } while (false);
}

-(void)AddComment:(FirCirCommentInfo *)fccinfo
{
    FirCirCommentInfo *oldfccinfo = [self.fccommentDS getCommentInfoByID:fccinfo.commentID];
    if (oldfccinfo == nil) {
        [self.fccommentDS SetCommentDic:fccinfo.commentID withObject:fccinfo];
        FriendStatus *fs = [self.fcnewsDS getNewsByID:fccinfo.newsID];
        if (fs != nil) {
            fs.commentsCount += 1;
            [fs.commentArr addObject:fccinfo.commentID];
        }
        
        [[DataBaseCtrol shareControl] AddComment:fccinfo];
    }
}

@end
